package com.gin.kotlin.gf2gamecommunity.routes

import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.toRoute
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.composable.ConfirmDialog
import com.gin.kotlin.gf2gamecommunity.composable.LoginDialog
import com.gin.kotlin.gf2gamecommunity.database.entity.GF2Account
import kotlinx.serialization.Serializable


/**
 * 扩展方法
 * @receiver [NavGraphBuilder]
 */
fun NavGraphBuilder.accountManage() = composable<AccountManageRoute>(
    // 从屏幕右侧进入，持续500毫秒
    enterTransition = { slideInHorizontally(tween(500)) { it } },
    // 从屏幕右侧退出，持续500毫秒
    exitTransition = { slideOutHorizontally(tween(500)) { it } }) {

    AccountManageComposable(route = it.toRoute())
}

@Serializable
data class AccountManageRoute(
    val id: Int = 1
)


@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun AccountManageComposable(route: AccountManageRoute) {
    // 对话框的打开状态
    val openLoginDialog = remember { mutableStateOf(false) }
    val dao = App.INSTANCE.database.gF2AccountDao()
    val showDelDialog = remember { mutableStateOf(false) }
    val selectedAccount = remember { mutableStateOf<GF2Account?>(null) }

    Scaffold(
        topBar = {
            TopAppBar(title = {
                Text("账号管理")
            }, actions = {
                IconButton(onClick = { openLoginDialog.value = true }) {
                    Icon(imageVector = Icons.Filled.Add, contentDescription = "添加账号")
                }
            }
            )
        }
    ) { innerPadding ->
        val modifier = Modifier.padding(innerPadding)

        val state = dao.listFlow().collectAsState(listOf())

        LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp), contentPadding = PaddingValues(4.dp), modifier = modifier) {
            items(items = state.value) { account ->
                AccountItem(account,
                    onRemove = {
                        selectedAccount.value = it
                        showDelDialog.value = true
                    },
                    modifier = Modifier
                        .height(40.dp)
                        .clickable {
                            dao.clearCurrent()
                            dao.setCurrent(account.uid)
                            App.INSTANCE.initApi()
                        }
                )
            }
        }

        when {
            showDelDialog.value -> {
                ConfirmDialog(
                    onDismissRequest = { showDelDialog.value = false },
                    onConfirmation = {
                        // 删除当前账号
                        selectedAccount.value?.apply {
                            dao.delete(uid)
                            App.INSTANCE.initApi()
                        }
                        showDelDialog.value = false
                    },
                ) {
                    selectedAccount.value?.apply {
                        Text("即将移除账号: $username")

                    }
                }
            }
        }
    }

    // 当 openLoginDialog 为 true时打开登录对话框
    when {
        openLoginDialog.value -> LoginDialog(
            api = App.buildApi().accountApi,
            onSuccess = { _, _, _ -> openLoginDialog.value = false },
            onCloseDialog = { openLoginDialog.value = false }
        )
    }
}

@Composable
fun AccountItem(data: GF2Account, onRemove: (GF2Account) -> Unit, modifier: Modifier = Modifier) {
    Row(horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = modifier
        .fillMaxWidth()
        .padding(horizontal = 4.dp)) {
        Text(data.username)
        Row(verticalAlignment = Alignment.CenterVertically) {
            if (data.current) {
                Icon(Icons.Filled.Check, contentDescription = "当前账号")
                Spacer(Modifier.width(10.dp))
            }
            Text("UID: ${data.uid}")
            Spacer(Modifier.width(10.dp))
            IconButton(onClick = { onRemove(data) }) {
                Icon(imageVector = Icons.Filled.Delete, contentDescription = "移除账号")
            }
        }
    }
}